package com.webex.ta.hydra.gui.macro;

import com.webex.ta.hydra.core.macro.MacroDefinition;

import javax.swing.*;
import java.util.Vector;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-9-14
 * Time: 15:37:48
 */
public class MacroListModel extends AbstractListModel {
    private Vector<MacroDefinition> defs = new Vector<MacroDefinition>();

    public void clear() {
        defs.clear();
        this.fireContentsChanged(this, 0, Integer.MAX_VALUE);
    }

    public int getSize() {
        return defs.size();
    }

    public Object getElementAt(int index) {
        return defs.get(index);
    }

    public void addElement(MacroDefinition def) {
        int index = defs.size();
        defs.addElement(def);
        fireIntervalAdded(this, index, index);
    }

    public int indexOf(Object elem) {
        return defs.indexOf(elem);
    }

    public boolean removeElement(Object obj) {
        int index = indexOf(obj);
        boolean rv = defs.removeElement(obj);
        if (index >= 0) {
            fireIntervalRemoved(this, index, index);
        }
        return rv;
    }

    public void removeElementAt(int index) {
	    defs.removeElementAt(index);
	    fireIntervalRemoved(this, index, index);
    }

    public MacroDefinition get(int index) {
        return defs.get(index);
    }

    public Vector<MacroDefinition> getDefinitions() {
        return defs;
    }

    public void setDefinitions(Vector<MacroDefinition> defs) {
        this.defs = defs;
        this.fireContentsChanged(this, 0, defs.size() - 1);
    }

    public boolean move(int idx, int direction ) {
        if (idx < 0 || idx >= defs.size()) // invalid index
            return false;

        if ((idx == 0 && direction<=0) || (idx == defs.size() -1 && direction >=0))
            // try to move up first row  or  move down last row
            return false;

        MacroDefinition des = defs.get(idx);
        defs.remove(idx);
        if (direction<0)
            defs.insertElementAt(des, idx-1);
        else if (direction > 0)
            defs.insertElementAt(des, idx+1);
        return true;
    }
}
